package com.powernode.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysUser;
import com.powernode.domain.SysUserRole;
import com.powernode.mapper.SysUserMapper;
import com.powernode.mapper.SysUserRoleMapper;
import com.powernode.util.AuthUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName SysUserService
 * @Description TODO
 * @Date 2024/07/21 20:14
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    /**
     *  新增管理员
     * @param sysUser 管理员信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        // 获取管理员密码
        String password = sysUser.getPassword();
        // 判断是否有值
        if (!StrUtil.isBlankIfStr(password)) {
            // 管理员密码使用 加密
            sysUser.setPassword(passwordEncoder.encode(password));
        }
        int count = sysUserMapper.insert(sysUser);
        if (count <= 0) {
            throw new RuntimeException("新增管理员失败");
        }
        // 新增角色信息
        Long userId = sysUser.getUserId();
        List<Long> roleIdList = sysUser.getRoleIdList();
        // 新增用户角色关联信息
        List<SysUserRole> sysUserRoleList = new ArrayList<>(roleIdList.size());
        for (Long roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoleList.add(sysUserRole);
        }
        boolean result = sysUserRoleService.saveBatch(sysUserRoleList);

        return result ? 1 : 0;
    }

    /**
     * 根据id查询管理员信息
     * @param id id
     * @return 结果
     */
    public SysUser querySysUserInfoById(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id));
        if (CollectionUtil.isNotEmpty(sysUserRoles)) {
            List<Long> roleIdList = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roleIdList);
        }

        return sysUser;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer modifySysUser(SysUser sysUser) {
        // 获取管理员ID
        Long userId = sysUser.getUserId();
        // 删除管理员原有的角色
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId)
        );
        // 获取管理员角色id集合
        List<Long> roleIdList = sysUser.getRoleIdList();
        // 判断角色id集合是否有值
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            // 创建管理员与角色关系集合对象
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            // 循环遍历角色id集合
            roleIdList.forEach(roleId -> {
                // 创建管理员与角色关系对象
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                // 将管理员与角色关系对象添加到管理员与角色关系集合中
                sysUserRoleList.add(sysUserRole);
            });
            // 批量添加 管理员与角色关系集合
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        // 获取管理员新密码
        String newPassword = sysUser.getPassword();
        // 判断新密码是否有值，如果有值：设置新密码，相反：密码不变
        if (!StrUtil.isBlankIfStr(newPassword)) {
            // 新密码加密
            String encodeNewPassword = passwordEncoder.encode(newPassword);
            sysUser.setPassword(encodeNewPassword);
        }
        return sysUserMapper.updateById(sysUser);
    }


    @Transactional(rollbackFor = Exception.class)
    public Integer removeSysUsersByUserIdList(List<Long> userIds) {
        // 批量删除指定管理员与角色的关系记录
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId,userIds)
        );
        // 批量删除指定管理员
        return sysUserMapper.deleteBatchIds(userIds);
    }
}
